<template>
  <div style="height: 100%;">
    <div ref="headerRef" class="change-role">
      <div class="change" @click="changeUser">切换角色</div>
      <div class="current-role">
        <img :src="currentUser.avatar" />
        <span>{{
          currentUser.name + (currentUser.author ? '（作者）' : '（游客）')
        }}</span>
      </div>
    </div>
    <div ref="commentDivRef" :style="wrapStyle" class="comment-wrap">
      <Comment
        :data="data"
        :user="currentUser"
        :props="props"
        :before-submit="submit"
        :before-like="like"
        :before-delete="deleteComment"
        :upload-img="uploadImg"
        @input="updateData"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import Comment from './comment/index.vue';
import author_img from '../assets/author.jpeg';
import baiyun_img from '../assets/baiyun.jpeg';
import heitu_img from '../assets/heitu.jpeg';


const EXAMPLE_DATA: any = [
  {
    _id: 1,
    content: '梦芸\n近况如何\n算来已有十月未见你\n甚是思念',
    visitor: {
      name: '我叫白云',
      avatar: baiyun_img,
    },
    createAt: '2020.11.24',
    likes: 1,
    liked: true,
    childrenComments: [
      {
        _id: 2,
        content:
          '此刻我能闻见漫天火药味道\n我随军藏身长江边一暗无天日的地窖底\n埋首台灯下写这些字却不知把心绪给寄向何地',
        visitor: {
          name: 'NARUTO',
          avatar: '',
        },
        createAt: '2020.11.25',
      },
      {
        _id: 3,
        content: '\n如磐石般坚毅',
        visitor: {
          name: '我叫黑土',
          avatar: heitu_img,
        },
        createAt: '2020.11.25',
        reply: {
          name: 'NARUTO',
          avatar: '',
        },
      },
    ],
  },
  {
    _id: 4,
    content: '我想时光亦是用来磨的\n细细地磨慢慢地磨\n总能磨出些许墨香来',
    visitor: {
      name: '我叫黑土',
      avatar: heitu_img,
    },
    createAt: '2020.12.5',
    childrenComments: [
      {
        _id: 5,
        content: '即使我鼻子已不灵\n眼睛生出疾\n侥幸你的照片还能辨出依稀',
        visitor: {
          name: 'NARUTO',
          avatar: '',
        },
        createAt: '2020.12.6',
      },
    ],
  },
];

const users = [
  {
    name: 'Stranger',
    avatar: author_img,
    author: true,
  },
  {
    name: '我叫白云',
    avatar: baiyun_img,
  },
  {
    name: '我叫黑土',
    avatar: heitu_img,
  },
  {
    name: 'NARUTO',
    avatar: '',
  },
];

const data: any = ref([]);
const props = {
  id: '_id',
  content: 'content',
  imgSrc: 'imgSrc',
  children: 'childrenComments',
  likes: 'likes',
  liked: 'liked',
  reply: 'reply',
  createAt: 'createAt',
  user: 'visitor',
};

const currentUser: any = ref({});
const wrapStyle = ref('');
const commentDivRef = ref();

const headerRef = ref();

onMounted(()=>{
  currentUser.value = users[0];
  addData(1);
  wrapStyle.value = `height: calc(100vh - ${headerRef.value.clientHeight + 20}px)`
});

const submit = async (newComment, parent, add) => {
  console.log('submit--->');
  const res: any = await new Promise((resolve) => {
    setTimeout(() => {
      resolve({ newComment, parent })
    }, 300)
  });

  add(Object.assign(res.newComment, { _id: new Date().getTime() }))
  //TODO 保存回复  res.newComment  res.parent
  console.log('addComment: ', res)
};

const like = async (comment) => {
  const res = await new Promise((resolve) => {
    setTimeout(() => {
      resolve(comment)
    }, 0)
  });
  //TODO res是原数据，可通过非运算更新数据库
  console.log('likeComment: ', res)
};

const uploadImg = async ({ file, callback }) => {
  const res = await new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.readAsDataURL(file)

    reader.onload = () => {
      resolve(reader.result)
    }

    reader.onerror = () => {
      reject(reader.error)
    }
  })

  callback(res)
  //TODO 上传图片
  console.log('uploadImg--->', res)
};

const deleteComment = async (comment, parent) => {
  const res = await new Promise((resolve) => {
    setTimeout(() => {
      resolve({ comment, parent })
    }, 300)
  })
  //TODO 删除 res.comment  res.parent
  console.log('deleteComment: ', res)
};

const changeUser = () => {
  const index = users.findIndex((c) => c.name === currentUser.value.name)

  currentUser.value = users[index === users.length - 1 ? 0 : index + 1]
  commentDivRef.value.scrollTo({ left: 0, top: 0, behavior: 'smooth' })
};

const addData = (times) => {
  setTimeout(() => {
    data.value = new Array(times).fill(EXAMPLE_DATA).flat(Infinity)
  }, 0)
};

const updateData = (res) => {
  data.value = res;
};
</script>

<style lang="less" scoped>
.scroll-style(
  @thumb: rgba(255, 255, 255, 0.6),
  @track: rgba(255, 255, 255, 0)
) {
  &::-webkit-scrollbar,
  &::-webkit-scrollbar-thumb,
  &::-webkit-scrollbar-track {
    border: none;
    box-shadow: none;
  }
  &::-webkit-scrollbar {
    width: 4px;
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 2px;
    background: @thumb;
  }
  &::-webkit-scrollbar-track {
    background: @track;
  }
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  font-size: 14px;
}

html,
body {
  height: 100%;
}

@media screen and (min-width: 320px) {
  html {
    font-size: calc(14px + 4 * ((100vw - 320px) / (1200 - 320)));
  }
}

@media screen and (min-width: 1200px) {
  html {
    font-size: 18px;
  }
}

.change-role {
  background: #1c2433;
  color: #eee;
  padding: 1rem;
  display: flex;
  justify-content: center;
  align-content: center;
  .change {
    cursor: pointer;
    padding: 0.4rem;
    margin-right: 2rem;
    font-size: 0.9rem;
    border: 1px solid #e99210;
    border-radius: 5px;
    user-select: none;
    &:hover {
      opacity: 0.9;
    }
  }
  .current-role {
    min-width: 15rem;
    color: #e99210;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px dashed #e99210;
    padding: 0 1rem;
    img {
      width: 1.5rem;
      height: 1.5rem;
      margin-right: 0.5rem;
      border: 1px solid #eee;
      border-radius: 50%;
    }
  }
}

.comment-wrap {
  overflow: auto;
  .scroll-style(#db8f1c, #b9b9b9);
}

@media screen and (min-width: 760px) {
  body {
    margin: 0 10%;
    border: 1px dashed #eee;
  }
}

@media screen and (max-width: 500px) {
  .change-role .current-role {
    min-width: 5rem;
    padding: 0 0.5rem;
  }
}
</style>
